#include "project.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <Shinygami/datatree.hpp>

QString GetNameFromPath(const QString& filepath)
{
  short lastSlash = 0;
  short lastPoint = 0;

  for (short i = 0 ; i < filepath.length() ; ++i)
  {
      if (filepath[i] == '/' || filepath[i] == '\\')
          lastSlash = i;
      else if (filepath[i] == '.')
          lastPoint = i;
  }
  if (lastSlash > lastPoint)
      lastPoint = -1;
  else
      lastPoint = (lastPoint - 1) - lastSlash;
  return (filepath.mid(lastSlash + 1, lastPoint));
}

QString GetPathFromFilepath(const QString& filepath)
{
    short lastSlash = 0;

    for (short i = 0 ; i < filepath.length() ; ++i)
    {
        if (filepath[i] == '/' || filepath[i] == '\\')
            lastSlash = i;
    }
    return (filepath.mid(0, lastSlash));
}

QString GetFilepathFromPath(const QString& filepath)
{
    short lastSlash = 0;

    for (short i = 0 ; i < filepath.length() ; ++i)
    {
        if (filepath[i] == '/' || filepath[i] == '\\')
            lastSlash = i;
    }
    return (filepath.mid(lastSlash + 1));
}

Project::Project(const QString &name, const QString &path)
{
    _name = name;
    _path = path;
}

Project::Project(const QString &path)
{
    DataTree*   file = DataTree::Factory::Yaml(path.toStdString());
    Data        data;

    if (!(file))
    {
        QMessageBox::warning(0, "Fatal Error", "Cannot load project '" + path + "' for some reason. Hey, don't look at me like that, error handling is a lot of work. And it's boring.");
        _loadedWithSuccess = false;
        return ;
    }
    data = Data(file);
    _loadedWithSuccess = true;
    _name = GetNameFromPath(path);
    _path = GetPathFromFilepath(path);
    if (!data["levels"].Nil())
    {
        Data::iterator current = data["levels"].begin();
        Data::iterator end     = data["levels"].end();

        for (; current != end ; ++current)
        {
            QString name = (*current).Key().c_str();
            QString path = (*current).Value().c_str();

            _levels << Level(name, path);
        }
    }
    delete file;
}

bool Project::Save()
{
    QString    filepath(_path + PATH_SLASH + _name + ".yml");
    QFile      file(filepath);
    YamlStream str;

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::warning(0, "Fatal Error", "Can't open file " + filepath);
        return (false);
    }
    if (_levels.count())
    {
        str.newBlock("levels");
        foreach (Level level, _levels)
        {
            QPair<QString, std::string> pair;

            pair.first  = level.first;
            pair.second = level.second.toStdString();
            str << pair;
        }
        str.endBlock();
    }

    QTextStream out(&file);
    QString     toWrite(str.str().c_str());

    out << toWrite;
    file.close();
    return (true);
}
